package com.mao.douyin.demo.apis.controller;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author maodong
 * @Email 598129643@qq.com
 * @create 2021-03-23 10:01
 */

public class Dy {
     String str="";
     String num="";
     String wz="";
     String strend = "";

    //获得视频的item_ids，也就是视频网址上的那个19位的数字串
    public void getNum()throws IOException {
        URL url = null;
        url = new URL(str);
        HttpURLConnection conn= null;
        conn = (HttpURLConnection)url.openConnection();
        conn.setDoOutput(true);

        try {
            conn.getResponseCode();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String realUrl=conn.getURL().toString();
        num=realUrl.substring(38,57);
    }
    //获得视频的地址https://aweme.snssdk.com/aweme开头的那个网址，并将网址中的playwm改为play
    public void getWZ()throws IOException{
        URL url= null;
        url = new URL("https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids="+num);
        try {
            BufferedReader reader=new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            String str="";
            while((line=reader.readLine())!=null){
                str+=line;
            }
            reader.close();
            wz="https://aweme.snssdk.com/aweme/v1/play"+str.substring(str.indexOf("/?video"),str.indexOf("&line=0"))+"&line=0";
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //解决https://aweme.snssdk.com/aweme开头的网址只能手机端访问才能跳转的问题
    //并获得跳转后的真正的无水印地址
    public void doGet()throws IOException{


        URL obj = new URL(wz);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        con.setRequestMethod("GET");
        // 设置请求头
        con.setRequestProperty("user-agent", "Mozilla/5.0 ");

        int responseCode = con.getResponseCode();

        parseResult(con.getInputStream(), "GB2312");
    }
    private void parseResult(InputStream inStream, String charSet) {
        try {
            InputStreamReader stream = new InputStreamReader(inStream, charSet);
            BufferedReader br = new BufferedReader(stream);
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            String str = response.toString();
            strend=str.substring(str.indexOf("http"),str.indexOf("\">F"));
            System.out.println(strend);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
